import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { Text, View, StyleSheet, Alert, ScrollView, ActivityIndicator, TouchableOpacity } from 'react-native';
import { Icon, List, ListItem, Button } from 'react-native-elements';
import Loader from './widgets/Loader';
import { getPrinterAddess, setPrinterAddress } from './clientStorage';
import { NavigationActions } from 'react-navigation';
import { listDevices, disconnect } from './printerUtils';
import { primaryColor, toast, isIOS } from './utils';

const styles = StyleSheet.create({
  button: {
    marginVertical: 32
  },
  config: {
    margin: 16
  }
});

class SettingsPage extends Component {
  static navigationOptions = ({navigation, screenProps}) => {
    return {
      title: `Printer`,
      tabBarLabel: `Printer`,
      tabBarIcon: ({tintColor}) => <Icon name='print' color={tintColor} size={24}/>
    };
  }
  state = { scanning: false }
  componentDidMount() {
    this.onScan();
    getPrinterAddess()
      .then(address => this.setState({selectAddress: address}))
  }
  onScan = () => {
    listDevices()
      .then(devices => {
        if (!devices||devices.length===0) {
          toast('None devices found');
        }

        this.setState({devices, scanning: false});
      })
      .catch(error => {
        toast(error);
        this.setState({scanning: false});
      })
    this.setState({scanning: true});
  }
  onSelectPrinter = (device) => {
    this.setState({selectAddress: device.address});
    setPrinterAddress(device.address);
    disconnect();
  }
  render() {
    return (
      <ScrollView>
        {!isIOS()&&<Text style={styles.config}>For Android devices, plase pair the printer at System settings first, pair password is: 0000</Text>}
        {this.state.scanning?<ActivityIndicator style={styles.button}/>:
          <List>
            {
              this.state.devices&&this.state.devices.map((device, index) =>
                <ListItem key={index} title={device.name} subtitle={device.address} onPress={()=>this.onSelectPrinter(device)}
                  rightIcon={{name:device.address===this.state.selectAddress?'check-box':'check-box-outline-blank', color:device.address===this.state.selectAddress?primaryColor:null}}/>) 
            }
          </List>
        }
        <Button style={styles.button} disabled={this.state.scanning}
          backgroundColor='white' color='black' title={this.state.scanning?'Scanning':'Scan'}
          onPress={this.onScan}/>
      </ScrollView>
    );
  }
}

export default SettingsPage;

